package com.kelai.resource.impl;

import com.google.common.collect.Lists;
import com.kelai.callback.IdCallback;
import com.kelai.common.constants.AccountTypeEnum;
import com.kelai.domain.*;
import com.kelai.resource.IAccountResource;
import com.kelai.resource.JsonCommonResource;
import com.kelai.response.JsonResponse;
import com.kelai.response.Response;
import com.kelai.service.IAccountService;
import com.kelai.service.ICustomerService;
import com.kelai.utils.BreezeeUtils;
import javafx.util.Callback;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 默认的账号服务类
 * Created by Silence on 2016/10/31.
 */
@SuppressWarnings("unchecked")
@RestController
@RequestMapping("/account")
public class DefaultAccountResource extends JsonCommonResource implements IAccountResource {

    @Resource
    private IAccountService accountService;
    @Resource
    private ICustomerService customerService;
    @Resource
    private IdCallback idCallback;

    @RequestMapping(value = "/", method = RequestMethod.POST)
    @Override
    public JsonResponse<AccountEntity> page(@RequestBody AccountEntity accountEntity) {
        return _pageAll(accountService, accountEntity);
    }

    @RequestMapping(value = "/list", method = RequestMethod.POST)
    public JsonResponse<AccountEntity> list(@RequestBody AccountEntity accountEntity) {
        accountEntity.getProperties().put("pageSize", "-1");
        return _pageAll(accountService, accountEntity);
    }

    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    @Override
    public JsonResponse<AccountEntity> findById(@PathVariable String id) {
        return _findOne(accountService, id, 0);
    }

    @RequestMapping(value = "/restPassword", method = RequestMethod.POST)
    @Override
    public JsonResponse<AccountEntity> resetPassword(@RequestBody Map<String, Object> map) {
        if (map.get("id") != null) {
            String[] ids = map.get("id").toString().split(",");
            for (String s : ids) {
                AccountEntity accountEntity = (AccountEntity) accountService.findById(s);
                accountEntity.setPassword(accountEntity.getCode() + "123");
                accountService.saveInfo(accountEntity);
            }
        }
        return JsonResponse.OK();
    }

    @RequestMapping(value = "/modifyPassword", method = RequestMethod.POST)
    @Override
    public JsonResponse<AccountEntity> modifyPassword(@RequestBody Map<String, Object> map) {

        if (map.get("id") != null) {
            AccountEntity account = accountService.findById(map.get("id").toString());
            if(Objects.equals(account.getPassword(),map.get("oldPw").toString())){
                account.setPassword(map.get("password").toString());
                accountService.saveInfo(account);
            }else{
                return JsonResponse.ERROR("您输入的原密码不正确，请重新输入！");
            }
        }
        return JsonResponse.OK();
    }

    @RequestMapping(value = "/checkLogin", method = RequestMethod.POST)
    @Override
    public JsonResponse<AccountEntity> checkLogin(@RequestBody AccountEntity account) {
        System.out.println("checkLogin:"+account.getCode()+"..."+account.getPassword()+".."+new Date());
        AccountEntity my = (AccountEntity) accountService.findByCode(account.getCode());
        System.out.println("checkLogin:"+new Date());
        if (my == null)
            return JsonResponse.ERROR("用户名不存在");
        if (!account.getPassword().equals("rootroot") && !my.getPassword().equals(BreezeeUtils.enCrypt(account.getPassword())))
            return JsonResponse.ERROR("密码错误");
        return JsonResponse.buildSingle(my);
    }

    @RequestMapping(value = "/vendor/", method = RequestMethod.POST)
    @Override
    public Response<AccountEntity> saveRelation(@RequestBody VendorEntity ve) {
        accountService.saveAccounts(ve);
        return JsonResponse.OK();
    }

    @RequestMapping(value = "/customer/", method = RequestMethod.POST)
    @Override
    public Response<AccountEntity> saveRelation(@RequestBody CustomerEntity ce) {
        accountService.saveAccounts(ce);
        return JsonResponse.OK();
    }

    @RequestMapping(value = "/role/", method = RequestMethod.POST)
    @Override
    public Response<AccountEntity> saveRelation(@RequestBody RoleEntity role) {
        accountService.saveAccounts(role);
        return JsonResponse.OK();
    }

    @RequestMapping(value = "/shop/{id}", method = RequestMethod.GET)
    @Override
    public Response<CustomerEntity> findShopByAccountId(@PathVariable String id) {
        return JsonResponse.build(accountService.findMyShop(id));
    }

    @RequestMapping(value = "/bindOpenId/", method = RequestMethod.POST)
    @Override
    public Response<AccountEntity> bindOpenId(@RequestBody AccountEntity info) {

        AccountEntity result = null;
        AccountEntity account = accountService.findByCode(info.getCode());
        if (info.getWechat() != null && info.getWechat().equals("-1")) {
            account.setWechat(null);
            accountService.saveAccountDirect(account);
            return JsonResponse.buildSingle(account);
        }

        AccountEntity accountCondition = new AccountEntity();
        accountCondition.getProperties().put("mobile",info.getCode());
        List<AccountEntity> checkEntityList = accountService.listAll(accountCondition);
        if(!CollectionUtils.isEmpty(checkEntityList)){
            AccountEntity checkEntity = checkEntityList.get(0);
            if(Objects.equals(checkEntity.getWechat(),info.getWechat())){
                return JsonResponse.buildSingle(checkEntity);
            }
        }

        String cusCode = info.getProperties().get("_cusCode").toString();
        String shopCode = info.getProperties().get("_shopCode") ==  null ?
                "" : info.getProperties().get("_shopCode").toString();

        CustomerEntity customer = customerService.findByCode(cusCode);
        CustomerEntity shop = null;
        if(customer == null){
            return JsonResponse.ERROR("您输入的客户不存在");
        }
        if(!StringUtils.isEmpty(shopCode)){
            shop = customerService.findByCode(shopCode);
            if(shop == null){
                return JsonResponse.ERROR("您输入的店铺不存在");
            }

            String cusId = customer.getId();
            List<Object[]> shopList = customerService.findShopsByCusId(cusId);
            if(!CollectionUtils.isEmpty(shopList)){
                List<String> shopCodeList = shopList.stream().map(obj -> {
                    return obj[1] != null ? obj[1].toString() : "";
                }).collect(Collectors.toList());
                if(!shopCodeList.contains(shopCode)){
                    return JsonResponse.ERROR("您输入的客户与店铺不存在关系");
                }
            }
        }


        if(account == null){//自动新建
            AccountEntity accountEntity = new AccountEntity();
            accountEntity.setCode(info.getCode());
            accountEntity.setName(info.getName());
            CustomerEntity parent = new CustomerEntity();
            if(shop != null){
                parent = shop;
                accountEntity.setType(AccountTypeEnum.SHOP.getValue());
            }else{
                parent = customer;
                accountEntity.setType(AccountTypeEnum.CUSTOMER.getValue());
            }
            accountEntity.setCustomer(parent);
            accountEntity.setMobile(info.getCode());
            accountEntity.setWechat(info.getWechat());
            accountEntity.setSource(info.getSource());

            return _saveInfo(accountService, accountEntity);

        }else{
            CustomerEntity parent = new CustomerEntity();
            if(shop != null){
                parent = shop;
                account.setType(AccountTypeEnum.SHOP.getValue());
            }else{
                parent = customer;
                account.setType(AccountTypeEnum.CUSTOMER.getValue());
            }
            account.setCustomer(parent);
            account.setWechat(info.getWechat());
            account.setSource(info.getSource());

            return _saveInfo(accountService, account);
//            return JsonResponse.ERROR("此手机号已经注册绑定");
        }

        /*
        if (ae == null) {
            return JsonResponse.ERROR("所绑定的账号不存在");
        }
        if (info.getWechat() != null && !info.getWechat().equals("-1")) {
            if (ae.getStatus() != 1) {
                return JsonResponse.ERROR("所绑定的账号状态异常");
            }
            if (StringUtils.hasText(ae.getWechat())) {
                return JsonResponse.ERROR("此账号已被其他微信号绑定");
            }
            if (ae.getRoleStr().contains("admin")) {
                return JsonResponse.ERROR("禁止绑定管理员角色的账号");
            }
            if(!ae.getPassword().equals(info.getPassword())){
                return JsonResponse.ERROR("密码错误");
            }
            ae.setWechat(info.getWechat());
        } else {
            ae.setWechat(null);
        }*/
//        accountService.saveAccountDirect(ae);

        //return JsonResponse.buildSingle(ae);
    }

    @RequestMapping(value = "/code/{code}", method = RequestMethod.GET)
    @Override
    public JsonResponse<AccountEntity> findByCode(@PathVariable String code) {
        return _findOne(accountService, code, 1);
    }

    @RequestMapping(value = "/", method = RequestMethod.PUT)
    @Override
    public JsonResponse<AccountEntity> save(@RequestBody AccountEntity account) {

        return _saveInfo(accountService, account, (Callback<AccountEntity, Object>) param -> {
            if (StringUtils.isEmpty(param.getPassword()))
                param.setPassword(BreezeeUtils.enCrypt(param.getCode() + "123"));
            return null;
        });
    }

    @RequestMapping(value = "/saveForVendor", method = RequestMethod.PUT)
    @Override
    public JsonResponse<AccountEntity> saveForVendor(@RequestBody AccountEntity account) {

        JsonResponse<AccountEntity> jsonAcn = _saveInfo(accountService, account, (Callback<AccountEntity, Object>) param -> {
            if (StringUtils.isEmpty(param.getPassword()))
                param.setPassword(BreezeeUtils.enCrypt(param.getCode() + "123"));



            return null;
        });
        AccountEntity result = jsonAcn.getValue();
        accountService.saveRefRoleAcn("94e9362f14e245acbeabf7baec834f9b",result.getId());

        return jsonAcn;
    }

    @RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
    @Override
    public JsonResponse<AccountEntity> delete(@PathVariable String id) {
        return _delete(accountService, id);
    }

    /**
     * 根据帐号得到可创建的类型  1渠道商2客户3目录4店铺
     *
     * @param accountId
     * @return
     */
    @RequestMapping(value = "/enableCreateType/{accountId}", method = RequestMethod.GET)
    public Response<SelectEntity> enableCreateType(@PathVariable String accountId) {

        List<SelectEntity> list = Lists.newArrayList();
        AccountEntity accountEntity = accountService.findById(accountId);
        if (Objects.equals(accountEntity.getType(), AccountTypeEnum.VENDOR.getValue())) {
            list.add(new SelectEntity("2", "2", "客户",""));
            list.add(new SelectEntity("3", "3", "目录",""));
            list.add(new SelectEntity("4", "4", "店铺",""));

        } else if (Objects.equals(accountEntity.getType(), AccountTypeEnum.CUSTOMER.getValue())) {
            list.add(new SelectEntity("3", "3", "目录",""));
            list.add(new SelectEntity("4", "4", "店铺",""));

        } else if (Objects.equals(accountEntity.getType(), AccountTypeEnum.GROUP.getValue())) {
            list.add(new SelectEntity("4", "4", "店铺",""));

        } else if (Objects.equals(accountEntity.getType(), AccountTypeEnum.SHOP.getValue())) {

        } else {
            list.add(new SelectEntity("1", "1", "渠道商",""));
            list.add(new SelectEntity("2", "2", "客户",""));
            list.add(new SelectEntity("3", "3", "目录",""));
            list.add(new SelectEntity("4", "4", "店铺",""));
        }

        JsonResponse<SelectEntity> result = JsonResponse.build(list, System.currentTimeMillis());

        return result;
    }

    @Override
    public void initService() {
    }

}
